//
//  KKCalendarView.m
//  SHDoctor
//
//  Created by Mac mini on 15/10/13.
//  Copyright © 2015年 ShiHeng. All rights reserved.
//

#import "KKCalendarView.h"

#pragma mark -
#pragma mark - KKCalendarViewCell Class

@interface KKCalendarViewCell()

- (void)setCellDataWithDay:(NSInteger)day month:(NSInteger)month year:(NSInteger)year;

@end

@implementation KKCalendarViewCell

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: CGRectMake(CGRectGetMinX(frame) + 0.5, CGRectGetMinY(frame) + 0.5, CGRectGetWidth(frame) - 1, CGRectGetHeight(frame) - 1)];
    if (self != nil) {
        
        self.backgroundColor = [UIColor whiteColor];
        
        CGFloat width = CGRectGetWidth(self.bounds);
        CGFloat height = CGRectGetHeight(self.bounds);
        
        UILabel* titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 26, 26)];
        titleLabel.center = CGPointMake(width/2, height/2);
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor darkGrayColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont systemFontOfSize: 16.0f];
        titleLabel.layer.cornerRadius = CGRectGetHeight(titleLabel.bounds)/2;
        titleLabel.layer.masksToBounds = YES;
        [self addSubview: titleLabel];
        _titleLabel = titleLabel;
        
        _pointView = [[UIImageView alloc] initWithFrame: CGRectMake(width/2 - 2, CGRectGetMaxY(titleLabel.frame) + 3, 4, 4)];
        _pointView.backgroundColor = [UIColor lightGrayColor];
        _pointView.layer.cornerRadius = 2;
        _pointView.layer.masksToBounds = true;
        [self addSubview: _pointView];
    }
    return self;
}

- (void)setIsToday:(BOOL)isToday {
    _isToday = isToday;
    
    _titleLabel.backgroundColor = _isToday ? [UIColor redColor]: [UIColor clearColor];
    _titleLabel.textColor = _isToday ? [UIColor whiteColor] : [UIColor darkGrayColor];
}

- (void)setHasTask:(BOOL)hasTask {
    _hasTask = hasTask;
    _pointView.backgroundColor = _hasTask ? [UIColor redColor] : [UIColor lightGrayColor];
}

- (void)setSelected:(BOOL)selected {
    [super setSelected: selected];
    
    _titleLabel.layer.borderColor = selected ? [UIColor colorWithHexString: @"66cccc"].CGColor : [UIColor clearColor].CGColor;
    _titleLabel.layer.borderWidth = selected ? 1 : 0;
}

- (void)setCellDataWithDay:(NSInteger)day month:(NSInteger)month year:(NSInteger)year {
    
    _titleLabel.text = [NSString stringWithFormat: @"%@", @(day)];
    
    NSString *dayString = [NSString stringWithFormat: day < 10 ? @"0%@":@"%@", @(day)];
    NSString *monthString = [NSString stringWithFormat: month < 10 ? @"0%@":@"%@", @(month)];
    
    _dateString = [NSString stringWithFormat: @"%@%@%@",@(year),monthString,dayString];
    _date = [self dateFromString: _dateString formatter: @"yyyyMMdd"];
}

static NSDateFormatter *dateFormatter;

- (NSDate *)dateFromString:(NSString *)dateString formatter:(NSString *)formatter {
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
    }
    [dateFormatter setDateFormat:formatter];
    return [dateFormatter dateFromString:dateString];
}

@end




@interface KKCalendarView() {
    
    UIView *_pannelView;
    
    UIBarButtonItem *_leftButton;
    UILabel *_titleLabel;
    UIBarButtonItem *_rightButton;
    
    
    NSMutableArray* _dayItemViews;
    CGSize _itemSize;
    
    NSCalendar *_calendar;
    
    Class _itemClass;
    NSInteger _currentDay;
    NSInteger _currentMonth;
    NSInteger _currentYear;
    
    NSInteger _dayOfToday;
    NSInteger _monthOfToday;
    NSInteger _yearOfToday;
    
    KKCalendarViewCell *_selectedDayView;
}

- (void)updateItemViews;
- (void)updateToolBarData;

- (void)getFirstWeekDayOfMonth:(NSInteger*)firstWeekDay totalDaysOfMonth:(NSInteger*)totalDays month:(NSInteger)month;

- (void)getFirstWeekDayOfMonth:(NSInteger *)firstWeekDay totalDaysOfMonth:(NSInteger *)totalDays month:(NSInteger)month year:(NSInteger)year;

@end

@implementation KKCalendarView

- (instancetype)init {
    
    CGFloat width = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    
    CGFloat itemWidth = width / 7;
    
    _itemSize = CGSizeMake(itemWidth, itemWidth);
    
    CGFloat height = 64;
    
    self = [super initWithFrame: CGRectMake(0, 0, width, height)];
    if (self) {
        
        UIToolbar *topBar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, width, 44)];
        topBar.barTintColor = [UIColor colorWithHexString: @"#175467"];
        {
            UIBarButtonItem *leftSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target: nil action: nil];
            leftSpace.width = 10;

            _leftButton = [[UIBarButtonItem alloc] initWithImage: [UIImage imageNamed:@"calendar_left"] style:UIBarButtonItemStylePlain target: self action: @selector(lastMonth:)];
            _leftButton.tintColor = [UIColor whiteColor];
            
            UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target: nil action: nil];
            
            _rightButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"calendar_Right"] style:UIBarButtonItemStylePlain target: self action: @selector(nextMonth:)];
            _rightButton.tintColor = [UIColor whiteColor];
            
            UIBarButtonItem *rightSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target: nil action: nil];
            rightSpace.width = 10;
            
            [topBar setItems: @[leftSpace, _leftButton, spaceItem, _rightButton, rightSpace]];
            
            _titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 120, 20)];
            _titleLabel.center = CGPointMake(CGRectGetWidth(topBar.bounds)/2, CGRectGetHeight(topBar.bounds)/2);
            _titleLabel.backgroundColor = [UIColor clearColor];
            _titleLabel.font = [UIFont systemFontOfSize: 16];
            _titleLabel.textAlignment = NSTextAlignmentCenter;
            _titleLabel.textColor = [UIColor whiteColor];
            [topBar addSubview: _titleLabel];
        }
        [self addSubview: topBar];
        
        UIView *weekDayBackgroundView = [[UIView alloc] initWithFrame: CGRectMake(0, CGRectGetMaxY(topBar.frame), width, 20)];
        weekDayBackgroundView.backgroundColor = [UIColor colorWithHexString: @"66cccc"];
        
        NSArray *weekDays = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
        for (NSUInteger index = 0; index < weekDays.count; index++) {
            
            UILabel* titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(itemWidth * index, 0, itemWidth, CGRectGetHeight(weekDayBackgroundView.bounds))];
            titleLabel.backgroundColor = [UIColor clearColor];
            titleLabel.textColor = [UIColor whiteColor];
            titleLabel.textAlignment = NSTextAlignmentCenter;
            titleLabel.font = [UIFont systemFontOfSize: 12.0f];
            titleLabel.text = weekDays[index];
            
            [weekDayBackgroundView addSubview: titleLabel];
        }
        [self addSubview: weekDayBackgroundView];
        
        {
            _pannelView = [[UIView alloc] initWithFrame: CGRectMake(0, CGRectGetMaxY(weekDayBackgroundView.frame), width, height - 64)];
            _pannelView.backgroundColor = [UIColor colorWithWhite: 0.95 alpha: 1.0];
//            _pannelView.backgroundColor = [UIColor whiteColor];
            _pannelView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
            [self addSubview: _pannelView];
        }
        
        _calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
        [self setSelectedDate: [NSDate date]];
        
        _dateFormatter = @"yyyyMMdd";
        _dayOfToday = _currentDay;
        _monthOfToday = _currentMonth;
        _yearOfToday = _currentYear;
        
        [self registerDayViewClass: nil];
        [self updateItemViews];
    }
    return self;
}

#pragma mark - Action methods

- (void)lastMonth:(UIBarButtonItem *)item {
    
    _currentMonth--;
    if (_currentMonth == 0) {
        _currentYear--;
        _currentMonth = 12;
    }
    [self updateItemViews];
}

- (void)nextMonth:(UIBarButtonItem *)item {
    
    _currentMonth++;
    if (_currentMonth > 12) {
        _currentYear++;
        _currentMonth = 1;
    }
    [self updateItemViews];
}

#pragma mark - Action methods

- (void)onClick:(KKCalendarViewCell*)item {
    
    [_selectedDayView setSelected: false];
    _selectedDayView = item;
    [_selectedDayView setSelected: true];
    
    if (_delegate && [_delegate respondsToSelector: @selector(calendarView:didSelectedCell:)]) {
        [_delegate calendarView: self didSelectedCell: _selectedDayView];
    }
}

#pragma mark - Private methods

- (void)updateItemViews {
    
    [self updateToolBarData];
    
    [_dayItemViews makeObjectsPerformSelector: @selector(removeFromSuperview)];
    [_dayItemViews removeAllObjects];
    _dayItemViews = [NSMutableArray array];
    
    NSInteger firstWeekday;
    NSInteger totalDayOfMonth;
    
    [self getFirstWeekDayOfMonth: &firstWeekday totalDaysOfMonth: &totalDayOfMonth month: _currentMonth year: _currentYear];
    
    //  更新Cell的UI
    
    CGFloat beginY =  0.0;
    CGFloat beginX =  _itemSize.width * (firstWeekday - 1);
    
    for (NSInteger i = 0; i < totalDayOfMonth; i++) {
        
        KKCalendarViewCell* dayItemView = [[_itemClass alloc] initWithFrame: CGRectMake(beginX, beginY, _itemSize.width, _itemSize.height)];
        [dayItemView setCellDataWithDay: i + 1 month: _currentMonth year: _currentYear];
        [dayItemView addTarget: self action: @selector(onClick:) forControlEvents: UIControlEventTouchUpInside];
        
        [_pannelView addSubview: dayItemView];
        [_dayItemViews addObject: dayItemView];
        
        firstWeekday++;
        
        if (firstWeekday == 8) {
            firstWeekday = 1;
            
            beginY += _itemSize.height;
        }
        else if(i == totalDayOfMonth - 1) {
            beginY += _itemSize.height;
        }
        beginX =  _itemSize.width * (firstWeekday - 1);
        
        if (_currentYear == _yearOfToday && _currentMonth == _monthOfToday && i + 1 == _dayOfToday) {
            dayItemView.isToday = true;
            [self onClick: dayItemView];
        }
        else {
            dayItemView.isToday = false;
        }
        
        if (_currentMonth != _monthOfToday && i == 0) {
            [self onClick: dayItemView];
        }
        
        if (_delegate && [_delegate respondsToSelector: @selector(calendarView:redrawCell:)]) {
            [_delegate calendarView: self redrawCell: dayItemView];
        }
    }
    
    NSInteger pannelViewHeight = (NSInteger)beginY;
    
    [self setFrame: CGRectMake(0, 0, CGRectGetWidth(self.bounds), 64 + pannelViewHeight + 10)];
    
    if (_updateHeightHandle) {
        _updateHeightHandle (CGRectGetHeight(self.bounds));
    }
}

- (void)updateToolBarData {
    
//    if (_currentMonth == 1) {
//        _leftButton.title = [NSString stringWithFormat: @"%@年%@月",@(_currentYear - 1),@(12)];
//        _rightButton.title = [NSString stringWithFormat: @"%@月",@(_currentMonth + 1)];
//    }
//    else if (_currentMonth == 12) {
//        _leftButton.title = [NSString stringWithFormat: @"%@月",@(_currentMonth - 1)];
//        _rightButton.title = [NSString stringWithFormat: @"%@年%@月",@(_currentYear + 1),@(1)];
//    }
//    else {
//        _leftButton.title = [NSString stringWithFormat: @"%@月",@(_currentMonth - 1)];
//        _rightButton.title = [NSString stringWithFormat: @"%@月",@(_currentMonth + 1)];
//    }
    _titleLabel.text = [NSString stringWithFormat: @"%@年%@月", @(_currentYear), @(_currentMonth)];
}

#pragma mark -
/**
 *  计算一个月总共的天数
 *
 *  @param beginTime 开始日期[格式为yyyy-MM-dd] NSString类型
 *  @param endTime   结束日期[格式为yyyy-MM-dd] NSString类型
 *
 *  @return 指定月份的天数
 */
- (NSInteger)dayOfMonthWithBeginTime:(NSString*)beginTime andWithEndTime:(NSString*)endTime {
    
    NSDateFormatter* dateFromatter=[[NSDateFormatter alloc] init];
    [dateFromatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *beginDate=[dateFromatter dateFromString: beginTime];
    NSDate *endDate=[dateFromatter dateFromString: endTime];
    
    return [self dayOfMonthWithBeginDate: beginDate andWithEndDate: endDate];
}

/**
 *  计算一个月总共的天数
 *
 *  @param beginDate 开始日期 NSDate类型
 *  @param endDate   结束日期 NSDate类型
 *
 *  @return 指定月份的天数
 */
- (NSInteger)dayOfMonthWithBeginDate:(NSDate*)beginDate andWithEndDate:(NSDate*)endDate {
    
    if (beginDate == nil || endDate == nil) {
        return 0;
    }
    
    NSTimeInterval beginLate=[beginDate timeIntervalSince1970]*1;
    NSTimeInterval endLate=[endDate timeIntervalSince1970]*1;
    
    NSTimeInterval offset = endLate - beginLate;
    
    return offset / (3600 * 24);
}

/**
 *  获取指定月份的第一天周几和总天数
 *
 *  @param firstWeekDay 第一天week的指针
 *  @param totalDays    总天数的指针
 *  @param month        指定的月份
 */
- (void)getFirstWeekDayOfMonth:(NSInteger*)firstWeekDay totalDaysOfMonth:(NSInteger*)totalDays month:(NSInteger)month {
    
    [self getFirstWeekDayOfMonth: firstWeekDay totalDaysOfMonth: totalDays month: month year: _currentYear];
}

/**
 *  获取指定月份的第一天周几和总天数
 *
 *  @param firstWeekDay 第一天week的指针
 *  @param totalDays    总天数的指针
 *  @param month        指定的月份
 *  @param year         指定的年份
 */
- (void)getFirstWeekDayOfMonth:(NSInteger *)firstWeekDay totalDaysOfMonth:(NSInteger *)totalDays month:(NSInteger)month year:(NSInteger)year {
    
    if (month > 12) {
        year++;
        month -= 12;
    }
    
    NSDateComponents *firstDayOfMonthComponents = [NSDateComponents new];
    firstDayOfMonthComponents.timeZone = [NSTimeZone timeZoneWithName: @"GMT"];
    firstDayOfMonthComponents.year = year;
    firstDayOfMonthComponents.month = month;
    firstDayOfMonthComponents.day = 1;
    NSDate *firstDayDateOfMonth = [_calendar dateFromComponents: firstDayOfMonthComponents];
    
    NSDateComponents *firstDayOfNextMonthComponents = [NSDateComponents new];
    firstDayOfNextMonthComponents.timeZone = [NSTimeZone timeZoneWithName: @"GMT"];
    firstDayOfNextMonthComponents.year = month == 12 ? year + 1 : year;
    firstDayOfNextMonthComponents.month = month == 12 ? 1 : month + 1;
    firstDayOfNextMonthComponents.day = 1;
    NSDate *firstDayDateOfNextMonth = [_calendar dateFromComponents: firstDayOfNextMonthComponents];
    
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit |
    NSWeekOfMonthCalendarUnit |
    NSWeekCalendarUnit |
    NSWeekdayOrdinalCalendarUnit;
    
    firstDayOfMonthComponents = [_calendar components: unitFlags fromDate: firstDayDateOfMonth];
    
    
    *firstWeekDay = firstDayOfMonthComponents.weekday;
    *totalDays = [self dayOfMonthWithBeginDate: firstDayDateOfMonth andWithEndDate: firstDayDateOfNextMonth];
}

#pragma mark - Public methods
/**
 *  设置默认的当前时间
 *
 *  @param selectedDate 设置当前时间
 */
- (void)setSelectedDate:(NSDate *)selectedDate {
    
    if (selectedDate == nil) {
        return;
    }
    
    _selectedDate = [selectedDate copy];
    
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents *currentComponents = [_calendar components: unitFlags fromDate: _selectedDate];
    
    _currentDay = currentComponents.day;
    _currentMonth = currentComponents.month;
    _currentYear = currentComponents.year;
}

/**
 *  注册dayItem的Class
 *
 *  @param cellClass  ItemCell
 */
- (void)registerDayViewClass:(nullable Class)cellClass {
    
    if (cellClass == nil || cellClass != [KKCalendarViewCell class]) {
        
        _itemClass = [KKCalendarViewCell class];
    }
    else {
        _itemClass = cellClass;
    }
}

/**
 *  刷新数据
 */
- (void)reloadData {
    
    [self updateItemViews];
}
@end
